// pages/addrecord/addrecord.js
var util = require('../../../../utils/util.js');
var calc = require("../../../../utils/calc.js");
var common = require("../../../../utils/common.js");
//获取应用实例
var app = getApp()
Page({
  data: {
    typeList:[],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 500,
    // 当前swiper页数
    swiperIndex:1,
    // 之前的选中项:[1,0]代表第1页的第0项
    oldTypeIndex:[1,0],
    memberArray: [],
    memberIndex: 0,
    paternArray: [],
    paternIndex: 0,
    date: "",
    money:"",
    content:"",
    address:"",
    remark:"",
    btnFinishLoading:false,
    btnAgainLoading:false,
    btnDeleteLoading:false,
    finishText:"保存",
    againText:"再记一笔",
    deleteText:"删除",
    id:null,
    kind:null,
    contentFocus:false,
    moneyFocus:true,
    // 计算器相关属性
    calHidden:true,
    calSrc:'/image/cal.png',
    idb:"back",
    idc:"clear",
    idt:"toggle",
    idadd:"＋",
    id9:"9",
    id8:"8",
    id7:"7",
    idj:"－",
    id6:"6",
    id5:"5",
    id4:"4",
    idx:"×",
    id3:"3",
    id2:"2",
    id1:"1",
    iddiv:"÷",
    id0:"0",
    idd:".",
    ide:"＝",
    screenData:"0",
    operaSymbo:{"＋":"+","－":"-","×":"*","÷":"/",".":"."},
    lastIsOperaSymbo:false,
    iconType:'download',
    iconColor:'white',
    arr:[],
    logs:[]
  },
  onLoad:function(options){
    var that = this;
    calc.reset()
    that.setData({
      id:options.id,
      kind:options.kind,
      date: util.formatDate(new Date)
    })

    if(app.globalData.recordParam){
      that.setData({
        typeList:app.globalData.recordParam.kind,
        paternArray:app.globalData.recordParam.patern
      })
      if(app.globalData.recordParam.member.length > 0){
        that.setData({
          memberArray:app.globalData.recordParam.member
        })
      }else{
        that.setData({
          memberArray:[{"member":"本人"}]
        })
      }
      that.detailData()
    }else{
      app.getRecordParam(function(paramRes){
        if(paramRes.status==1){
          that.setData({
            typeList:paramRes.data.kind,
            paternArray:paramRes.data.patern
          })
          if(paramRes.data.member.length > 0){
            that.setData({
              memberArray:paramRes.data.member
            })
          }else{
            that.setData({
              memberArray:[{"member":"本人"}]
            })
          }
          that.detailData()
        }else{
          app.errorToGetToken()
        }
      })
    }

    if(!options.id&&app.globalData.paternIndex){
      console.log('-------------'+app.globalData.swiperIndex+'------'+app.globalData.memberIndex+'-------'+app.globalData.paternIndex+'------'+app.globalData.oldTypeIndex)
      // 先设置滑动动画时长0
      that.setData({
        duration:0,
        // contentFocus:false
      })
      that.setData({
        //设置全局变量
        // type轮播图列表
        typeList:app.globalData.typeList,
        // kind的序号
        swiperIndex:app.globalData.swiperIndex,
        // 之前的选中项:[1,0]代表第1页的第0项
        oldTypeIndex:app.globalData.oldTypeIndex,
        // 成员的序号
        memberIndex:app.globalData.memberIndex,
        // 方式的序号
        paternIndex:app.globalData.paternIndex,
      })
      // 再设置滑动动画时长500
      that.setData({
        duration:500,
        // contentFocus:false
      })
    }
    
  },
  itemNameClick: function(e) {
    // 把之前的选中清掉
    var list = this.data.typeList;
    list[this.data.oldTypeIndex[0]].type[this.data.oldTypeIndex[1]].selected = false;
    
    // 把选中的设进去
    list[this.data.swiperIndex].type[e.currentTarget.dataset.index].selected = true;
    this.setData({
      typeList: list
    })
    // 更新oldTypeIndex
    this.setData({
      oldTypeIndex: [this.data.swiperIndex,e.currentTarget.dataset.index]
    })
    // console.log(e.currentTarget.dataset.index)
    
  },
  bindChange: function(e) {
      this.setData({
      swiperIndex: e.detail.current
    })
  },
  memberPickerChange: function(e) {
    this.setData({
      memberIndex: e.detail.value
    })
  },
  paternPickerChange: function(e) {
    this.setData({
      paternIndex: e.detail.value
    })
  },
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  btnComplete: function(e) {
    var that = this
    // 设置按钮加载状态
    this.setData({
      btnFinishLoading:true,
      finishText:"正在保存"
    })
    if(that.data.id==null){//添加
      that.submitData(function(res){
          //更新按钮状态
          that.setData({
            btnFinishLoading:false,
            finishText:"保存"
          })
        if(res.status==-1){
        }else{
          //刷新上一页数据
          var pages = getCurrentPages();
          if(pages.length > 1){
              //上一个页面实例对象
              var prePage = pages[pages.length - 2];
              prePage.getData()
          }
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }else{//修改
      that.editData(function(res){
          //更新按钮状态
          that.setData({
            btnFinishLoading:false,
            finishText:"保存"
          })
        if(res.status==-1){
        }else{
          //刷新上一页数据
          var pages = getCurrentPages();
          if(pages.length > 1){
              //上一个页面实例对象
              var prePage = pages[pages.length - 2];
              prePage.getData()
          }
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }
      
  },
  btnAddAgain: function(e) {
    var that = this
    //设置按钮加载状态
    this.setData({
      btnAgainLoading:true,
      againText:"正在保存"
    })
    this.submitData(function(res){
        //更新按钮状态
        that.setData({
          btnAgainLoading:false,
          againText:"再记一笔"
        })
      if(res.status==-1){
      }else{
        //刷新上一页数据
        var pages = getCurrentPages();
        if(pages.length > 1){
            //上一个页面实例对象
            var prePage = pages[pages.length - 2];
            prePage.getData()
        }
        //清除数据
        that.setData({
          money:"",
          content:"",
          address:"",
          remark:""
        })
      }
    })
  },
  btnDelete: function(e) {
    var that = this
    // 设置按钮加载状态
    // this.setData({
    //   btnDeleteLoading:true,
    //   deleteText:"正在删除"
    // })
    that.deleteRecord(function(res){
      //更新按钮状态
      // that.setData({
      //   btnDeleteLoading:false,
      //   deleteText:"删除"
      // })
      if(res.status==-1){
      }else{
        //刷新上一页数据
        var pages = getCurrentPages();
        if(pages.length > 1){
            //上一个页面实例对象
            var prePage = pages[pages.length - 2];
            prePage.getData()
        }
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  submitData: function(cb) {
    var that = this;
    var kind = that.data.typeList[that.data.oldTypeIndex[0]].kind
    var recordType = that.data.typeList[that.data.oldTypeIndex[0]].type[that.data.oldTypeIndex[1]].name
    var money = that.data.money
    var member = that.data.memberArray[that.data.memberIndex].member
    var patern = that.data.paternArray[that.data.paternIndex].cardtype
    var date = that.data.date
    var content = that.data.content
    var address = that.data.address
    var remark = that.data.remark

    var returnRes = null
    if(money=="") {
      wx.showModal({
        title: '错误提示',
        content: '请填写正确的金额',
        showCancel:false
      })
      returnRes = {
      "status":-1,
      "msg":"请填写正确的金额"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }
    // if(kind=="支出"&&content=="") {
    //   // console.log(kind)
    //   wx.showModal({
    //     title: '错误提示',
    //     content: '请填写内容',
    //     showCancel:false
    //   })
    //   returnRes = {
    //   "status":-1,
    //   "msg":"请填写正确的内容"
    //   }
    //   typeof cb == "function" && cb(returnRes)
    //   return
    // }
    if(kind=="支出"&&(content+"").length>10) {
      wx.showModal({
        title: '错误提示',
        content: '内容不能超出10个字，详细信息可写入"备注"',
        showCancel:false
      })
      returnRes = {
      "status":-1,
      "msg":"请填写正确的内容"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }
    
    wx.request({
      url: common.apiUrl()+'addRecord',
      data: {
        token:app.globalData.wangcaiToken,
        kind:kind,
        recordtype:recordType,
        money:money,
        member:member,
        patern:patern,
        date:date,
        content:content,
        address:address,
        remark:remark
      },
      method:'POST',
      header: {
      'content-type': 'application/x-www-form-urlencoded'
        },
      success: function(res){
        if(res.data.status==1){
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            success: function(e){
              //设置全局变量
              // kind的序号
              app.globalData.typeList=that.data.typeList
              app.globalData.swiperIndex=that.data.swiperIndex
              // 之前的选中项:[1,0]代表第1页的第0项
              app.globalData.oldTypeIndex= that.data.oldTypeIndex
              // 成员的序号
              app.globalData.memberIndex= that.data.memberIndex
              // 方式的序号
              app.globalData.paternIndex=that.data.paternIndex
              typeof cb == "function" && cb(res.data)
            }
          })
        }else{
          app.errorToGetToken()
        }
      }
    })
  },
  editData: function(cb) {
    var that = this;
    var kind = that.data.typeList[that.data.oldTypeIndex[0]].kind
    var recordType = that.data.typeList[that.data.oldTypeIndex[0]].type[that.data.oldTypeIndex[1]].name
    var money = that.data.money
    var member = that.data.memberArray[that.data.memberIndex].member
    var patern = that.data.paternArray[that.data.paternIndex].cardtype
    var date = that.data.date
    var content = that.data.content
    var address = that.data.address
    var remark = that.data.remark

    var returnRes = null
    if(money=="") {
      wx.showModal({
        title: '错误提示',
        content: '请填写正确的金额',
        showCancel:false
      })
      returnRes = {
      "status":-1,
      "msg":"请填写正确的金额"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }
    // if(kind=="支出"&&content=="") {
    //   // console.log(kind)
    //   wx.showModal({
    //     title: '错误提示',
    //     content: '请填写内容',
    //     showCancel:false
    //   })
    //   returnRes = {
    //   "status":-1,
    //   "msg":"请填写正确的内容"
    //   }
    //   typeof cb == "function" && cb(returnRes)
    //   return
    // }
    if(kind=="支出"&&(content+"").length>10) {
      wx.showModal({
        title: '错误提示',
        content: '内容不能超出10个字，详细信息可写入"备注"',
        showCancel:false
      })
      returnRes = {
      "status":-1,
      "msg":"请填写正确的内容"
      }
      typeof cb == "function" && cb(returnRes)
      return
    }
    
    wx.request({
      url: common.apiUrl()+'editRecord',
      data: {
        token:app.globalData.wangcaiToken,
        oldkind:that.data.kind,
        id:that.data.id,
        kind:kind,
        recordtype:recordType,
        money:money,
        member:member,
        patern:patern,
        date:date,
        content:content,
        address:address,
        remark:remark
      },
      method:'POST',
      header: {
      'content-type': 'application/x-www-form-urlencoded'
        },
      success: function(res){
        if(res.data.status==1){
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            success: function(e){
              //设置全局变量
              // kind的序号
              app.globalData.typeList=that.data.typeList
              app.globalData.swiperIndex=that.data.swiperIndex
              // 之前的选中项:[1,0]代表第1页的第0项
              app.globalData.oldTypeIndex= that.data.oldTypeIndex
              // 成员的序号
              app.globalData.memberIndex= that.data.memberIndex
              // 方式的序号
              app.globalData.paternIndex=that.data.paternIndex
              typeof cb == "function" && cb(res.data)
            }
          })
        }else{
          app.errorToGetToken()
        }
      }
    })
  },
  detailData: function(e) {
    var that = this
    // 如果id有值，请求该id记录详情信息
    if(that.data.id!=null){
      // 设置滑动动画时长
      that.setData({
        duration:0,
        moneyFocus:false
        // contentFocus:false
      })
      wx.request({
        url: common.apiUrl()+'recordDetail',
        data: {
          token:app.globalData.wangcaiToken,
          kind:that.data.kind,
          id:that.data.id
        },
        success: function(res){
          // 把之前的选中清掉
          var list = that.data.typeList;
          list[that.data.oldTypeIndex[0]].type[that.data.oldTypeIndex[1]].selected = false;
          // kind 1 支出 kind2 收入
          var kind = that.data.kind==1?'支出':'收入'
          for(var i=0;i<list.length;i++){
            if(list[i].kind==kind){
              for(var j=0;j<list[i].type.length;j++){
                if(list[i].type[j].name==res.data.data.type){
                  // 更新oldTypeIndex
                  that.setData({
                    swiperIndex:i,
                    oldTypeIndex:[i,j]
                  })
                  // 把选中的设进去
                  list[i].type[j].selected = true;
                  that.setData({
                    typeList: list
                  })
                  break
                }
              }
            }
          }
          for(var i=0;i<that.data.memberArray.length;i++){
            if(that.data.memberArray[i].member==res.data.data.member){
              // 设置memberIndex值
              that.setData({
                memberIndex:i
              })
              break
            }
          }
          for(var i=0;i<that.data.paternArray.length;i++){
            if(that.data.paternArray[i].cardtype==res.data.data.cardtype){
              // 设置paternIndex值
              that.setData({
                paternIndex:i
              })
              break
            }
          }

          that.setData({
            date:util.formatDate(new Date(res.data.data.date)),
            content:res.data.data.name,
            money:res.data.data.money,
            address:res.data.data.address,
            remark:res.data.data.remark
          })
          // 设置滑动动画时长
          that.setData({
            duration:500
          })
        }
      })
    }
  },
  deleteRecord:function(cb){
    var that = this
    wx.showActionSheet({
      itemList: ['删除'],
      itemColor: '#E64340',
      success: function(res) {
        switch(res.tapIndex){
          case 0:
            // kind＝1，支出，kind＝2，收入
            var kind = "expense"
            if(that.data.kind==2){
              kind = "income"
            }
            wx.request({
              url: common.hostUrl()+ kind +'/delete',
              data: {
                ids:that.data.id
              },
              method:'POST',
              header: {
              'content-type': 'application/x-www-form-urlencoded'
                },
              success: function(res){
                if(res.data.status==1){
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success',
                    success: function(e){
                      // 刷新数据
                      typeof cb == "function" && cb(res.data)
                    }
                  })
                }else{
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'success'
                  })
                }
              }
            })
          break;
          case 1:

          break;
        }
      },
      fail: function(res) {
        that.setData({
          clickId:""
        })
      }
    })
  },
  cal:function(e){
    var that=this
    // wx.hideKeyboard()
    that.setData({
        calHidden:!that.data.calHidden,
        calSrc:that.data.calSrc == '/image/cal.png'?'/image/cal_selected.png':'/image/cal.png'
      })
  },
  calPanel:function(e){

  },
  touchStart:function(e){
    var that=this
    that.setData({
      calHidden:true,
      calSrc:'/image/cal.png'
    })
  },
  moneyFocus: function(e) {
    
  },
  moneyInput: function(e) {
    this.setData({
      money: e.detail.value
    })
  },
  contentInput: function(e) {
    this.setData({
      content: e.detail.value
    })
  },
  addressInput: function(e) {
    this.setData({
      address: e.detail.value
    })
  },
  remarkInput: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  // 计算器按钮
  clickBtn:function(event){
    var id = event.target.id;
    if(id == this.data.idb){  //退格←
      var data = this.data.screenData;
      if(data == "0"){
          return;
      }
      data = data.substring(0,data.length-1);
      if(data == "" || data == "－"){
          data = 0;
      }
      this.setData({"screenData":data});
      this.data.arr.pop();
    }else if(id == this.data.idc){  //清屏C
      this.setData({"screenData":"0"});
      this.data.arr.length = 0;
    }else if(id == this.data.idt){  //正负号+/-
      var data = this.data.screenData;
      if(data == "0"){
          return;
      }
      var firstWord = data.charAt(0);
      if(data == "－"){
        data = data.substr(1);
        this.data.arr.shift();
      }else{
        data = "－" + data;
        this.data.arr.unshift("－");
      }
      this.setData({"screenData":data});
    }else if(id == this.data.ide){  //等于＝
      var data = this.data.screenData;
      if(data == "0"){
          return;
      }
      //eval是js中window的一个方法，而微信页面的脚本逻辑在是在JsCore中运行，JsCore是一个没有窗口对象的环境，所以不能再脚本中使用window，也无法在脚本中操作组件                 
      //var result = eval(newData);           
      
      var lastWord = data.charAt(data.length);
      if(isNaN(lastWord)){
        return;
      }

      var num = "";

      var lastOperator = "";
      var arr = this.data.arr;
      var optarr = [];
      for(var i in arr){
        if(isNaN(arr[i]) == false || arr[i] == this.data.idd || arr[i] == this.data.idt){
          num += arr[i];
        }else{
          lastOperator = arr[i];
          optarr.push(num);
          optarr.push(arr[i]);
          num = "";
        }
      }
      optarr.push(Number(num));
      var result = Number(optarr[0])*1.0;
      // console.log(result);
      for(var i=1; i<optarr.length; i++){
        if(isNaN(optarr[i])){
            if(optarr[1] == this.data.idadd){
                result += Number(optarr[i + 1]);
            }else if(optarr[1] == this.data.idj){
                result -= Number(optarr[i + 1]);
            }else if(optarr[1] == this.data.idx){
                result *= Number(optarr[i + 1]);
            }else if(optarr[1] == this.data.iddiv){
                result /= Number(optarr[i + 1]);
            }
        }
      }
      //存储历史记录
      this.data.logs.push(data + result);
      wx.setStorageSync("calclogs",this.data.logs);

      this.data.arr.length = 0;
      this.data.arr.push(result);

      this.setData({"screenData":result+""});
    }else{
      if(this.data.operaSymbo[id]){ //如果是符号+-*/
        if(this.data.lastIsOperaSymbo || this.data.screenData == "0"){
          return;
        }
      }

      var sd = this.data.screenData;
      var data;
      if(sd == 0){
        data = id;
      }else{
        data = sd + id;
      }
      this.setData({"screenData":data});
      this.data.arr.push(id);

      if(this.data.operaSymbo[id]){
        this.setData({"lastIsOperaSymbo":true});
      }else{
        this.setData({"lastIsOperaSymbo":false});
      }
    }
  },
  giveMoney:function(e){
    var that=this
    if (isNaN(that.data.screenData)) {
　　　　return;
　　}
    that.setData({
      money:that.data.screenData
    })
  }
})